package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.example.utils.SystemUtil;

import android.Manifest;

import java.util.ArrayList;
import java.util.Set;

public class BluetoothDeviceListActivity extends AppCompatActivity {
    private static final String TAG = "DeviceListActivity";
    private ArrayAdapter<String> pairedDevicesArrayAdapter;
    private ListView pairedListView;
    private BluetoothAdapter bluetoothAdapter;

    //设置监听事件
    private Button scanButton;
    AdapterView.OnItemClickListener l = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        }
    };
    private ArrayList<String> requestList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_device_list);
        Intent data = getIntent();
        String printType = data.getStringExtra(SettingActivity.PRINT_TYPE);

        scanButton = findViewById(R.id.button_scan);
        scanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doDiscovery();
            }
        });


        pairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_item);
        pairedListView = findViewById(R.id.paired_devices);
        pairedListView.setAdapter(pairedDevicesArrayAdapter);

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        // todo 蓝牙动态申请权限

        requestList = new ArrayList<>();
        checkPermission();
        Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); //获取已配对的设备
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice pairedDevice : pairedDevices) {
                String deviceName = pairedDevice.getName();
                if (!SystemUtil.isInputCorrect(deviceName)) {
                    pairedDevicesArrayAdapter.add(pairedDevice.getName()
                            + "已配对"
                            + "\n" + pairedDevice.getAddress());
                }
            }

        }

        pairedListView.setOnItemClickListener(l);

    }

    /**
     * 开始搜索
     */
    private void doDiscovery() {
        Log.d(TAG, "doDiscovery()");

        checkPermission();
        bluetoothAdapter.startDiscovery();
        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }
        pairedDevicesArrayAdapter.clear();
        bluetoothAdapter.startDiscovery();
        scanButton.setText("正在搜索中...");
        scanButton.setEnabled(false);

    }
    private void checkPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                // Android 版本大于等于 Android12 时
                // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
                requestList.add(Manifest.permission.BLUETOOTH_SCAN);
                requestList.add(Manifest.permission.BLUETOOTH_ADVERTISE);
                requestList.add(Manifest.permission.BLUETOOTH_CONNECT);
            } else {
                // Android 版本小于 Android12 及以下版本
                requestList.add(Manifest.permission.ACCESS_COARSE_LOCATION);
                requestList.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }

            if (requestList.size() > 0) {
                ActivityCompat.requestPermissions(this, requestList.toArray(new String[0]), 1001);
            }
        }

    }

    private BroadcastReceiver bulethReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (intent != null && action.equals(BluetoothDevice.ACTION_FOUND)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                checkPermission();
                Log.d(TAG, "find name :" + device.getName());
                String name = device.getName();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(bulethReceiver,filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(bulethReceiver);
    }
}